﻿using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using EzDesk.Apps.Interface.ProjectModule;
using EzDesk.Apps.Model.ProjectModule;
using EzDesk.Apps.ServiceImpl.ProjectModule;
using EzDesk.Core.Model;
using EzDesk.EzAppApi.Utility;
using EzDesk.Utility.Extensions;
using EzDesk.Utility.ServiceStatusInfo;
using System.Text;
using EzDesk.Utility;
using EzDesk.Utility.Web.Extensions;
using EzDesk.Clients.DesktopWeb.ViewModels;

namespace EzDesk.Clients.DesktopWeb.Controllers
{
    public partial class ProjectController
    {

        #region Page


        public ActionResult ProjectTemplate()
        {
            return View(new object());
        }

        public ActionResult ProjectList()
        {
            var hasPermissionToCreateProject = EzApiClient.UserHasPermission("PROJECT_CREATE_PROJECT", CurrentUserId);

            dynamic model = new ExpandoObject();

            List<Project> projectList = null;
            projectList = hasPermissionToCreateProject ? 
                ProjectService.GetProjects(null, null).Result : 
                ProjectService.GetProjects(CurrentUserId, null).Result;
            var projectModelList = getProjectListModel(projectList);
            model.ProjectList = projectModelList;
            model.HasCreateProjectPermission = hasPermissionToCreateProject;

            return View("ProjectList", model);
        }

        //todo: 等完善了再给一个统一入口
        public ActionResult ProjectInfo(Guid id)
        {
            return RedirectToAction("ProjectWorkitems", new { Id = id });
        }

        public ActionResult ProjectMembers(Guid id)
        {
            //todo:
            dynamic model = new ExpandoObject();
            var project = ProjectService.GetProjectById(id).Result;

            var memberList = project.MemberInProject.Select(
                p =>
                {
                    var roleStr = "member";
                    if (p.UserId == project.ChargePersonId) roleStr = "leader";
                    if (p.UserId == project.CreatorId) roleStr = "creator";

                    return new
                    {
                        Member = EzApiClient.GetSimpleUserById(p.UserId),
                        Role = roleStr
                    };
                }).ToList();
            var leader = memberList.FirstOrDefault(p => p.Member.Id == project.ChargePersonId);
            var creator = memberList.FirstOrDefault(p => p.Member.Id == project.CreatorId);

            var projectModel = new
            {
                Id = project.Id,
                Name = project.Name,
                Code = project.Code,
                project.Description,
                CreateOn = project.CreateOn,
                Leader = leader,
                Creator = creator,
                MemberList = memberList,
            };

            model.ProjectInfo = projectModel;
            return View(model);
        }

        public ActionResult ProjectWorkitems(Guid id)
        {
            dynamic model = new ExpandoObject();
            var project = ProjectService.GetProjectById(id).Result;
            var memberList = project.MemberInProject.Select(p => EzApiClient.GetSimpleUserById(p.UserId))
                                                    .ToList();
            model.ProjectInfo = new
            {
                Id = project.Id,
                Name = project.Name,
                Code = project.Code,
                CreateOn = project.CreateOn,
                project.Description,
                MemberList = memberList,
                project.Task
            };

            return View(model);
        }

        #endregion Page

        #region [ Partial Actions ]
        public ActionResult _createProjectShortcut(bool hasCreateProjectPermission)
        {
            return hasCreateProjectPermission ? View() : null;
        }

        public ActionResult _projectTemplates(bool hasCreateProjectPermission)
        {
            return hasCreateProjectPermission ? View() : null;
        }
        #endregion

        #region Ajax

        [HttpGet]
        public ActionResult GetFullProjectById(Guid id)
        {
            var project = ProjectService.GetFullProjectById(id).Result;
            project.TeamMembers = EzApiClient.GetSimpleUserInfos(project.MemberString);
            if (project.ChargePersonId.HasValue)
                project.Director = EzApiClient.GetSimpleUserById(project.ChargePersonId.Value);


            project.Workitem.Foreach(wi => wi.PopulateCreatorNameAndOwnerName());

            return Json(project, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult DoUpdateProjectMemberString(Guid projectId, string memberString)
        {
            var originalMemberList = EzApiClient.GetSimpleUserInfos(
                    ProjectService.GetProjectById(projectId).Result.MemberString
                ).ToList();
            var newMemberList = EzApiClient.GetSimpleUserInfos(memberString).ToList();

            var addMemberList = newMemberList.Where(p => !originalMemberList.ContainUser(p)).ToList();
            var removeMemberList = originalMemberList.Where(p => !newMemberList.ContainUser(p)).ToList();

            //todo: 重构这个代码。。。

            var sb = new StringBuilder();
            int i = 0;
            foreach (var simpleUser in addMemberList)
            {
                if (i < 3)
                {
                    if (i != 0) sb.Append(", ");
                    sb.Append(simpleUser.Name);
                }
                else
                {
                    sb.AppendFormat(" 等{0}人", addMemberList.Count);
                    break;
                }
                i++;
            }
            if (i > 0)
            {
                sb.Append(" 被添加进项目组");
            }
            var addMemberString = sb.ToString();

            sb = new StringBuilder();
            i = 0;
            foreach (var simpleUser in removeMemberList)
            {
                if (i < 3)
                {
                    if (i != 0) sb.Append(", ");
                    sb.Append(simpleUser.Name);
                }
                else
                {
                    sb.AppendFormat(" 等{0}人", removeMemberList.Count);
                    break;
                }
                i++;
            }
            if (i > 0)
            {
                sb.Append(" 被从项目组中移除");
            }
            var removeMemberString = sb.ToString();

            var statusInfo = ProjectService.UpdateProjectMember(projectId, memberString);
            if (statusInfo.Status == ServiceStatus.Success)
            {
                statusInfo.Info = string.Format("{0} {1}", addMemberString, removeMemberString);
            }
            return Json(statusInfo);
        }

        /// <summary>
        /// 更新项目基本信息方法，参数 = null 则不更新，空字符串也会被更新
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="projectName"></param>
        /// <param name="projectCode"></param>
        /// <param name="description"></param>
        /// <returns></returns>
        [HttpPost]
        [PermissionRequire("PROJECT_EDIT_PROJECT_BASICINFO")]
        public ActionResult DoUpdateProjectBasicInfo(Guid projectId, string projectName,string projectCode, string description)
        {
            var statusInfo = ProjectService.UpdateProjectBasicInfo(projectId, projectName, projectCode, description);
            if (statusInfo.Status == ServiceStatus.Success)
            {
                statusInfo.Info = "更新完成";
            }
            return Json(statusInfo);
        }


        [HttpPost]
        public ActionResult DoCreateProject(string projectName, string projectCode, Guid chargeUserId, Guid? projectTemplateId,string planOn)
        {
            var memberString = "";
            memberString = EzDeskAppApiHelper.MemberStringHelper.JoinUserId(memberString, CurrentUserId);
            memberString = EzDeskAppApiHelper.MemberStringHelper.JoinUserId(memberString, chargeUserId);

            var project = new Project()
            {
                Name = projectName,
                Code = projectCode,
                Description = "",
                ChargePersonId = chargeUserId,
                MemberString = memberString,
                CreatorId = CurrentUserId,
            };
            var planOnDate = string.IsNullOrEmpty(planOn)
                                      ? DateTime.Today
                                      : Convert.ToDateTime(planOn);

            project.PlanOn = planOnDate;

            var statusInfo = 
                projectTemplateId.HasValue
                ? ProjectService.CreateNewProjectWithTemplate(project, projectTemplateId.Value, planOnDate) 
                : ProjectService.CreateNewProject(project);

            if (statusInfo.Status == ServiceStatus.Success)
            {
                statusInfo.Info = "创建项目成功";
                statusInfo.Data = new { projectId = statusInfo.Result.Id.ToString() };
            }
            return Json(statusInfo.ToSimpleStatusInfo());
        }

        [HttpGet]
        public JsonResult GetProjectListForUser(Guid? userId)
        {
            if (!userId.HasValue)
            {
                userId = CurrentUserId;
            }
            var projectList = ProjectService.GetProjectsForUser(userId.Value).Result;
            
            return Json(projectList, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public JsonResult GetAllProjects()
        {
            var projectList = ProjectService.GetProjects(null, null).Result;
            return Json(projectList, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public JsonResult GetSimpleProjectListForUser(Guid? userId)
        {
            if (!userId.HasValue)
            {
                userId = CurrentUserId;
            }
            var projectList = ProjectService.GetProjectsForUser(userId.Value).Result;

            var projectModel = projectList.Select(project => new
            {
                project.Name,
                project.Id
            });

            return Json(
               projectModel,
               JsonRequestBehavior.AllowGet
               );
        }

        [HttpPost]
        public JsonResult CreateProjectTemplate(string projectTemplateStr)
        {
            var projectTemplate = WebJsonExtension.FromJson<ProjectTemplate>(projectTemplateStr);
            var statusInfo = ProjectService.CreateProjectTemplate(projectTemplate);
            if (statusInfo.Status == ServiceStatus.Success)
            {
                statusInfo.Info = "项目模板创建成功";
            }
            return Json(statusInfo);
        }

        [HttpGet]
        public JsonResult GetProjectTemplateList()
        {
            var statusInfo = ProjectService.GetProjectTemplateList();
            if (statusInfo.Status == ServiceStatus.Success)
            {
                return Json(statusInfo.Result);
            }
            return Json("[]");
        }

        [HttpPost]
        public JsonResult ChangeProjectStartOn(Guid projectId, long startOn)
        {
            var startOnDateTime =  EpochDateTimeExtension.FromEpoch(startOn);
            var statusInfo = ProjectService.ChangeProjectStartOn(projectId, startOnDateTime);
            return Json(statusInfo);   
        }

        [HttpPost]
        public JsonResult RemoveProjectTemplate(Guid id)
        {
            var statusInfo = ProjectService.RemoveProjectTemplate(id);
            return Json(statusInfo);
        }

        #endregion Ajax

        #region Private Methods

        private List<dynamic> getProjectListModel(List<Project> projectList)
        {
            var projectModelList = new List<dynamic>();

            foreach (var project in projectList)
            {
                var memberList = project.MemberInProject.Select(
                    p =>
                    {
                        var roleStr = "member";
                        if (p.UserId == project.ChargePersonId) roleStr = "leader";
                        if (p.UserId == project.CreatorId) roleStr = "creator";
                        return new
                        {
                            Member = EzApiClient.GetSimpleUserById(p.UserId),
                            Role = roleStr
                        };
                    }).ToList();
                var leader = memberList.FirstOrDefault(p => p.Member.Id == project.ChargePersonId);

                var projectModel = new
                {
                    Id = project.Id,
                    Name = project.Name,
                    ProjectId = project.Code,
                    Explanation = project.Description,
                    CreatOn = project.CreateOn,
                    Leader = leader,
                    MemberList = memberList,
                };
                projectModelList.Add(projectModel);
            }

            return projectModelList;
        }

        #endregion
    }
}
